import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
Vue.use(VueRouter);
const routes = [
  // 一级路由
  { path: "/", redirect: "/layout" },
  {
    // 登录页面
    path: "/login",
    //路由懒加载 当访问这个路由的时候才回去加载对应的文件
    // 提高首页加载
    component: () => import("@/views/Login"),
  },
  {
    // 首页
    path: "/layout",
    component: () => import("@/views/Layout"),
    redirect: "/layout/home",
    children: [
      // 二级路由
      {
        // 文章页面展示
        path: "home",
        component: () => import("@/views/Layout/Home"),
      },
      {
        // 用户页面展示
        path: "user",
        component: () => import("@/views/Layout/User"),
      },
    ],
  },
  {
    // 搜索页面
    path: "/search",
    component: () => import("@/views/Search"),
  },
  {
    // 搜索文章详情页
    path: "/search/:name",
    component: () => import("@/views/Search/SearchResult"),
  },
  {
    // 文章详情页
    path: "/article",
    component: () => import("@/views/ArticleDetail"),
  },
  {
    // 编辑用户资料页
    path: "/user_edit",
    component: () => import("@/views/Layout/User/UserEdit"),
  },
  {
    // 小思同学页
    path: "/chat",
    component: () => import("@/views/Chat"),
  },
];

const router = new VueRouter({
  routes,
});

// 把不需要登录就可以访问的路由路径写在这个数组中
// 白名单数组
const whiteList = ["/login", "/layout/home", "/search"];
//把需要登录就可以访问的路由路径写在这个数组中
// const authList=[]

//1.路由的全局前置守卫
router.beforeEach((to, from, next) => {
  const { token } = store.state.user;
  if (token) {
    next();
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirectUrl=${to.path}`);
    }
  }
});

export default router;
